<template>
	<view class="container">
		<view class="content">
			<view class="content-top d-rn d-ac">
				<view class="content-top-left">
					<image :src="baseUel + user.avatar" mode=""></image>
				</view>
				<view class="content-top-right">
					<view class="content-top-right-top d-rn d-ac">
						<text>{{ user.employeeName }}{{ $t('user_employeeName_attendance') }}</text>
						<text>{{ user.positionName }}</text>
					</view>
					<view class="content-top-right-bto">
						<text
							class="one-txt-cut"
							style="max-width: 500rpx; display: block"
							>{{ user.employerNames }}</text
						>
					</view>
				</view>
			</view>
			<view class="rili">
				<!-- <view class="rili-top d-rn d-ac d-jb">	
          <picker
            @change="bindPickerChange"
            :range="banciList"
            range-key="shiftName"
            class="picker"
          >
            <view class="d-rn d-ac d-jc">
              <view class="picker-con d-cn d-jc d-ac">
                <view class="uni-input one-txt-cut" v-if="type.typeName"
                  >{{ type.typeName }}
                </view>
                <view class="uni-input one-txt-cut" v-else>请选择</view>
              </view>
              <image
                src="../../static/img/bottom.png"
                mode=""
                class="bottom"
              ></image>
            </view>
          </picker>
          <view class="" style="color: #eeeeee"> | </view>
          <view class="">
            <u-search
              placeholder="请输入班次名字"
              v-model="searchValue"
              @search="handleSearch"
              @custom="handleSearch"
            ></u-search>
          </view>
        </view> -->
				<view class="">
					<view class="rili">
						<u-calendar
							:dateLists="dateList"
							ref="calendar"
							:maxDate="maxDate"
							:minDate="minDate"
							:nowMonth="nowMonth"
							@handleGetRiFather="handleGetRiFather"
							@handleGetMonth="handleGetMonth"
							@geyheights="geyheights"
							@changeYear="changeYear"
							:yearsNum="yearsNum"
						></u-calendar>
					</view>
				</view>
			</view>
			<view class="list" v-if="allDay">
				<view
					class="list-one"
					v-for="(item, index) in kaoqinlist"
					:key="index"
				>
					<view class="clockIn-order-daka d-rn d-jb">
						<view class="clockIn-order-daka-left">
							<view
								class="clockIn-order-daka-left-top d-rn d-ac"
								style="width: 100%"
							>
								<text
									>{{$t('clockIn_order_signIn')}}：{{
										item.signInTime
											? item.signInTime
											: $t('no_clock_in_records')
									}}</text
								>
								<text
									v-if="
										item.kaoqinList &&
										item.kaoqinList.find(
											(v) => v.punchForm == 1
										) &&
										item.kaoqinList.find(
											(v) => v.punchForm == 1
										).isOutWork == 1 &&
										item.signInTime
									"
									class="isOutWork"
									>{{ $t('user_employeeName_fieldClockIn') }}</text
								>
								<text
									@click="handleDaKa(item, 1)"
									v-if="
										item.signInTime &&
										item.submitAmendmentRequest == 1
									"
									>{{ $t('apply_for_modify') }}</text
								>
								<!-- <text @click="handleBuKa(item, 1)"
									v-if="!item.signInTime && item.cardReplacement == 1">补卡申请</text> -->

								<text
									@click="handleBuKa(item, 1)"
									v-if=" !item.signInTime && item.cardReplacement == 1 && canBuKa"
									>{{ $t('reissue_card') }}</text
								>
								<!-- <text @click="handleJiaBan(item)">加班申请</text> -->
							</view>
							<view
								class="clockIn-order-daka-left-min"
								v-if="item.shiftName"c
							>
								<text>{{$t('clockIn_order_shiftName')}}：{{ item.shiftName }}</text>
							</view>
							<view class="clockIn-order-daka-left-bto d-rn d-ac">
								<image
									src="../../static/img/address.png"
									mode=""
								></image>
								<text class="w-80">{{
									item.signInAddress
								}}</text>
							</view>
							<view
								class="clockIn-order-daka-left-mark d-rn d-ac"
								v-if="item.signInRemark"
							>
								<text>{{$t('clockIn_order_remark')}}：{{ item.signInRemark }}</text>
							</view>
						</view>
						<view class="clockIn-order-daka-image">
							<image :src="item.signInPic" mode=""></image>
						</view>
					</view>
					<view class="clockIn-order-daka d-rn d-jb">
						<view class="clockIn-order-daka-left">
							<view
								class="clockIn-order-daka-left-top d-rn d-ac"
								style="width: 100%"
							>
								<text
									>{{$t('clockIn_order_signOut')}}：{{
										item.signOutTime
											? item.signOutTime
											: $t('no_clock_in_records')
									}}</text
								>
								<text
									v-if="
										item.kaoqinList &&
										item.kaoqinList.find(
											(v) => v.punchForm == 2
										) &&
										item.kaoqinList.find(
											(v) => v.punchForm == 2
										).isOutWork == 1 &&
										item.signOutTime
									"
									class="isOutWork"
									>{{ $t('user_employeeName_fieldClockIn') }}</text
								>
								<text
									@click="handleDaKa(item, 2)"
									v-if="
										item.signOutTime &&
										item.submitAmendmentRequest == 1
									"
									>{{$t('apply_for_modify')}}</text
								>
								<!-- <text @click="handleBuKa(item, 2)"
										v-if="!item.signOutTime && item.cardReplacement == 1">补卡申请</text> -->
								<text
									@click="handleBuKa(item, 2)"
									v-if="!item.signOutTime && item.cardReplacement == 1 && canBuKa"
									>{{$t('reissue_card')}}</text
								>
								<text
									@click="handleJiaBan(item)"
									class="text-style"
									v-if="overTimeRule != 3"
									>{{$t('clockIn_apply_overtime')}}</text
								>
							</view>
							<view
								class="clockIn-order-daka-left-min"
								v-if="item.shiftName"
							>
								<text>{{$t('clockIn_order_shiftName')}}：{{ item.shiftName }}</text>
							</view>
							<view class="clockIn-order-daka-left-bto d-rn d-ac">
								<image
									src="../../static/img/address.png"
									mode=""
								></image>
								<text class="w-80">{{
									item.signOutAddress
								}}</text>
							</view>
							<view
								class="clockIn-order-daka-left-mark d-rn d-ac"
								v-if="item.signOutRemark"
							>
								<text>{{$t('clockIn_order_note')}}：{{ item.signOutRemark }}</text>
							</view>
						</view>
						<view class="clockIn-order-daka-image">
							<image :src=" item.signOutPic" mode=""></image>
						</view>
					</view>
				</view>
			</view>
			<view class="total">
				<view class="title">
					<view>
						{{
							getAttendanceSummary(yearsNum, nowMonth)
								.isCurrentMonth
								? $t('current_month')
								: numberToMonthChinese(nowMonth) + $t('month')
						}}{{ $t('attendance_data_summary') }}
					</view>
					<view style="font-size: 12px; margin: 5px 0">{{
						getAttendanceSummary(yearsNum, nowMonth).dateRange
					}}</view>
				</view>
				<view class="total-title d-rn d-ac d-jc">
					<text
						>{{ $t('attendance_data') }} <text>{{ vaInfo.attendanceDays }}</text> {{$t('days')}}，{{ $t('hour_statistics') }}
						<text>{{ vaInfo.hours || 0 }}</text> {{ $t('hours') }}</text
					>
				</view>
				<view>
					<u-grid :border="false" col="3">
						<u-grid-item
							v-for="(listItem, listIndex) in list"
							:key="listIndex"
							class="total-one"
						>
							<text>{{ listItem.name || 0 }}</text>
							<text class="grid-text">{{ listItem.title }}</text>
						</u-grid-item>
					</u-grid>
					<u-grid :border="false" col="3">
						<u-grid-item
							v-for="(listItem, listIndex) in holidayList"
							:key="listIndex"
							class="total-one"
						>
							<text>{{ listItem.name || 0 }}</text>
							<text class="grid-text">{{ listItem.title }}</text>
						</u-grid-item>
					</u-grid>
					<u-toast ref="uToast" />
				</view>
			</view>

			<!-- <view class="save d-rn d-ac d-jc" v-if="allDay">
        <text>保存考勤记录到相册</text>
      </view> -->
		</view>
		<u-picker
			:show="changeYearShow"
			:columns="columns"
			@cancel="changeYearShow = false"
			@confirm="changeYearConfirm"
			:defaultIndex="defaultIndex"
		></u-picker>
	</view>
</template>

<script>
var _self;
import {
	getAttendance,
	getAttendanceRecordList,
	classesList,
	getPersonHolidays,
} from '../../api/index.js';
import request from '../../utils/request.js';

export default {
	data() {
		return {
			changeYearShow: false,
			allDay: false,
			hostList: [],
			type: {
				typeName: '',
				typeId: '',
			},
			searchValue: '',

			list: [
				{
					name: '1',
					title: this.$t('late_count'),
				},
				{
					name: '2',
					title: this.$t('leave_early_count'),
				},
				{
					name: '0',
					title: this.$t('absence_count'),
				},
				{
					name: '3',
					title: this.$t('missing_punch_count'),
				},
				{
					name: '4',
					title: this.$t('serious_late_count'),
				},
				{
					name: '5',
					title: this.$t('serious_leave_early_count'),
				},
			],
			holidayList: [],
			listss: [
				{
					month: '1',
					date: [
						{
							day: '1',
							sts: 0,
						},
						{
							day: '2',
							sts: 1,
						},
						{
							day: '3',
							sts: 2,
						},
						{
							day: '4',
							sts: 3,
						},
						{
							day: '5',
							sts: 4,
						},
					],
				},
			],
			maxDate: '',
			minDate: '',
			kaoqinlist: [],
			hasPage: false,
			total: 0,
			totalPage: 0,
			pageNum: 1,
			pageSize: 3,
			nowMonth: null,
			mode: 'multiple',
			years: '',
			nowMonths: '',
			workday: '',
			userName: '',
			workdays: '',
			banciList: [],
			dateList: [],
			vaInfo: {},
			baseUel: request.common.baseUrl,
			user: uni.getStorageSync('userInfo'),
			dateRecord: {},
			columns: [
				[
					2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024,
					2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034,
					2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044,
					2045,
				],
			],
			defaultIndex: 0,
			id: '',
			overTimeRule: '',
			yearsNum: 0,
			// 是否可以补卡标志
			canBuKa: true,
		};
	},
	onLoad(e) {
		this.overTimeRule = JSON.parse(e.data).overTimeRule;
		console.log('this.overTimeRule', this.overTimeRule);
		_self = this;
		var today = new Date();
		let year = today.getFullYear();
		_self.years = year;
		this.yearsNum = year;
		_self.nowMonth = today.getMonth();
		_self.day = today.getDate();
		_self.nowMonths = _self.nowMonth + 1;

		if (_self.nowMonths < 10) {
			_self.nowMonths = '0' + _self.nowMonths;
		}
		if (_self.day < 10) {
			_self.day = '0' + _self.day;
		}
		_self.workday = year + '-' + _self.nowMonths + '-' + _self.day;
		_self.workdays = year + '-' + _self.nowMonths + '-' + '01';
		_self.maxDate = year + '-12-31';
		_self.minDate = year + '-1-1';
		if (_self.workday) {
			_self.handlelist();
		}
		_self.getclassesList();
		_self.getgetAttendanceRecordList();
		this.defaultIndex = [
			this.columns[0].findIndex((v) => v == new Date().getFullYear()),
		];
		// _self.getList()
	},
	onShow() {
		_self.userName = uni.getStorageSync('empName');
		_self.pic = uni.getStorageSync('empic');
	},

	methods: {
		numberToMonthChinese(number) {
			var monthNames = [
				'一',
				'二',
				'三',
				'四',
				'五',
				'六',
				'七',
				'八',
				'九',
				'十',
				'十一',
				'十二',
			];
			if (number >= 1 && number <= 12) {
				return monthNames[number - 1];
			} else {
				return this.$t('please_enter_month_number');
			}
		},
		getAttendanceSummary(year, month) {
			var today = new Date();
			var currentYear = today.getFullYear();
			var currentMonth = today.getMonth() + 1;
			var endDate;
			var isCurrentMonth = false;

			if (year === currentYear && month === currentMonth) {
				endDate = today.getDate() - 1;
				isCurrentMonth = true;
			} else {
				// 获取指定年份和月份的最后一天
				endDate = new Date(year, month, 0).getDate();
			}

			var startDate = year + '-' + month + '-01';
			var endDateFormatted;
			if (isCurrentMonth) {
				endDateFormatted = year + '-' + month + '-' + endDate;
			} else {
				endDateFormatted = year + '-' + month + '-' + endDate;
			}

			return {
				dateRange: startDate + '~' + year + '-' + month + '-' + endDate,
				isCurrentMonth: isCurrentMonth,
			};
		},
		changeYearConfirm(e) {
			console.log('e', e);
			this.years = e.value[0];
			this.yearsNum = e.value[0];
			this.changeYearShow = false;
			this.workdays = `${this.years}-${
				this.nowMonth < 10 ? '0' + this.nowMonth : this.nowMonth
			}-${this.day}`;
			if (_self.workday) {
				_self.handlelist();
			}
			_self.getclassesList();
			_self.getgetAttendanceRecordList();

			this.userData = uni.getStorageSync('userInfo');
		},
		changeYear(flag) {
			this.changeYearShow = flag;
			console.log('点击了年份');
		},
		getList() {
			getPersonHolidays().then((res) => {
				if (res.code == 200) {
					// _self.list = res.data.vacationScheduleList
					_self.dateList.forEach((item) => {});
					// _self.list
				}
			});
		},
		// h获取班次
		getclassesList() {
			classesList().then((res) => {
				if (res.code == 200) {
					_self.banciList = res.data;
				}
			});
		},
		getgetAttendanceRecordList() {
			this.list.forEach((item) => {
				item.name = '';
			});
			this.dateList = [];
			let date = _self.workdays;
			console.log('获取打卡记录', date);
			getAttendanceRecordList({
				month: date,
				classesId: _self.type.typeId,
				classesName: _self.searchValue,
			}).then((res) => {
				console.log('🐛 ~ getgetAttendanceRecordList ~ res:', res);
				this.holidayList = [];
				if (res.data.vacationList && res.data.vacationList.length) {
					this.holidayList = res.data.vacationList.map((v, i) => {
						let keys = Object.keys(v);
						return {
							title: keys[0],
							name: v[keys[0]],
						};
					});
				}

				this.vaInfo = res.data;
				this.dateList = res.data.daysList;
				// if (this.dateList && this.dateList.length) {
				// 	this.dateList.forEach((item) => {
				// 		console.log("🐛 ~ this.dateList.forEach ~ item:", item)
				// 		// item.day = item.workday.substring(8, 10);
				// 		item.month = Number(item.day.substring(5, 7).replace('0',''));
				
				// 		// item.day = Number(item.day);
				// 		// item.month = Number(item.month);	
				// 	});
				// }
				if (this.dateList && this.dateList.length) {
				    this.dateList.forEach((item) => {
							// 考勤记录不要展示班次
								item.classesList = [];
				        // item.day = item.day.substring(8, 10).replace('0','');
								// item.date = item.
				        item.month = item.day.substring(5, 7).replace('0','');
				        // item.day = Number(item.day);
				        // item.month = Number(item.month);
				    });
				}
				console.log(
					'🐛 ~ getgetAttendanceRecordList ~ this.dateList:',
					this.dateList
				);

				this.list.forEach((item) => {
					if (item.title == this.$t('late_count')) {
						item.name = this.vaInfo.late;
					}
					if (item.title == this.$t('leave_early_count')) {
						item.name = this.vaInfo.leaveEarly;
					}
					if (item.title == this.$t('absence_count')) {
						item.name = this.vaInfo.absenteeism;
					}
					if (item.title == this.$t('missing_punch_count')) {
						item.name = this.vaInfo.lostCard;
					}
					if (item.title == this.$t('serious_late_count')) {
						item.name = this.vaInfo.lateSerious;
					}
					if (item.title == this.$t('serious_leave_early_count')) {
						item.name = this.vaInfo.leaveEarlySerious;
					}
					if (item.title == this.$t('sick_leave_days')) {
						item.name = this.vaInfo.sickLeave;
					}
					if (item.title == this.$t('personal_leave_days')) {
						item.name = this.vaInfo.leaveOfAbsence;
					}
					if (item.title == this.$t('maternity_leave_days')) {
						item.name = this.vaInfo.paternityLeave;
					}
				});

				this.$forceUpdate();
			});
		},

		bindPickerChange(e) {
			_self.type.typeName = _self.banciList[e.detail.value].classesName;
			_self.type.typeId = _self.banciList[e.detail.value].id;
			this.dateList = [];
			this.$forceUpdate();
			// _self.getgetAttendanceRecordList()
		},
		handleSearch() {
			_self.getgetAttendanceRecordList();
		},
		handleBuKa(paiInfo, punchType) {
			paiInfo.punchDate = _self.workday;
			paiInfo.punchType = punchType;
			this.$commonFun.goUrl(1, '../reissue/index', paiInfo);
		},
		handleDaKa(paiInfo, punchType) {
			paiInfo.punchType = punchType;
			this.$commonFun.goUrl(1, '../updateDaka/index', paiInfo);
		},
		handleJiaBan(item) {
			console.log('item', item, this.paiInfo);
			item.isDay = true;
			item.overTimeRule = this.overTimeRule;
			item.punchDate = this.workday;
			_self.$commonFun.goUrl(1, '../overtime/index', item);
		},
		handleGetRiFather(e) {
			_self.workday = e[0];

			_self.handlelist();
		},
		geyheights(e) {
			console.log('geyheights==', e);
		},
		handleGetMonth(e) {
			console.log('e', e);
			this.nowMonth = e + 1;
			let date = new Date();
			if (e < 10) {
				e = '0' + (e + 1);
			}

			let newDate = this.yearsNum + '-' + e + '-' + '01';
			console.log('新日期', newDate);
			_self.workdays = newDate;
			_self.handlelist();
			_self.getgetAttendanceRecordList();
		},

		handlelist() {
			getAttendance({
				pageNum: _self.pageNum,
				pageSize: _self.pageSize,
				punchDate: _self.workday,
			}).then((res) => {
				if (res.code == 200) {
					console.log('考勤记录', res.data);
					if (res.data && res.data.length) {
						_self.kaoqinlist =
							res.data[0].attendanceRecordShiftDTOList;
						_self.kaoqinlist.forEach((e, index) => {
							e.kaoqinList =
								res.data[0].attendanceRecordShiftDTOList[
									index
								].detailList;
						});

						console.log('	_self.kaoqinlist', _self.kaoqinlist);
						_self.allDay = !!res.data.length;
						this.id = res.data[0].id;
					} else {
						_self.kaoqinlist = [];
						_self.allDay = !!res.data.length;
					}

					// 如果新日期大于系统当前时间不可不卡

					// 获取当前时间年月日
					let nowDate = new Date();
					let nowYear = nowDate.getFullYear();
					let nowMonth = nowDate.getMonth() + 1;
					let nowDay = nowDate.getDate();
					// 拼接成yyyy-mm-dd格式
					let nowDateStr = `${nowYear}-${
						nowMonth < 10 ? '0' + nowMonth : nowMonth
					}-${nowDay < 10 ? '0' + nowDay : nowDay}`;

					if (
						new Date(this.workday).getTime() >
						new Date(nowDateStr).getTime() - 1000 * 60 * 60 * 24
					) {
						_self.canBuKa = false;
					} else {
						_self.canBuKa = true;
					}
					//   _self.total = res.total;

					//   _self.kaoqinlist.map((item) => {
					//     item.officeHours = item.officeHours.substring(10, 16);
					//   });

					//   _self.totalPage = _self.pageNum * _self.pageSize;
					//   if (_self.totalPage > res.total) {
					//     _self.hasPage = false;
					//   } else {
					//     _self.hasPage = true;
					//   }
				}
			});
		},
	},
	onReachBottom() {
		if (_self.hasPage) {
			_self.pageNum++;
			_self.hasPage = false;
			_self.handlelist();
		}
	},
};
</script>

<style lang="scss">
page {
	background-color: #f5f5f5;
}

.container {
	width: 100%;

	.content {
		&-top {
			width: 100%;
			margin: 24rpx auto;
			padding: 20rpx;
			box-sizing: border-box;
			background-color: #ffffff;

			&-left {
				margin-right: 24rpx;

				image {
					width: 110rpx;
					height: 110rpx;
				}
			}

			&-right {
				&-top {
					text:nth-of-type(1) {
						font-size: 36rpx;
						font-weight: bold;
						color: #333333;
						margin-right: 20rpx;
					}

					text:nth-of-type(2) {
						padding: 6rpx;
						box-sizing: border-box;
						font-size: 20rpx;
						font-weight: bold;
						color: #ff8f1f;
						background-color: #ffefdf;
						border-radius: 12rpx;
					}
				}

				&-bto {
					margin-top: 14rpx;

					text {
						color: #999999;
					}
				}
			}
		}

		.rili {
			background-color: #ffffff;
			height: 860rpx;

			&-top {
				padding: 22rpx;
				box-sizing: border-box;

				.bottom {
					width: 16rpx;
					height: 8rpx;
					margin-left: 10rpx;
				}
			}
		}

		.total {
			width: 100%;
			background-color: #ffffff;
			margin-top: 70rpx;
			padding: 22rpx;
			box-sizing: border-box;
			.title {
				text-align: center;
				font-weight: bold;
			}

			&-title {
				margin-bottom: 36rpx;

				text {
					font-size: 32rpx;
					color: #333333;
					font-weight: bold;

					text {
						font-size: 42rpx;
					}
				}
			}

			&-one {
				margin-bottom: 30rpx !important;

				text:nth-of-type(1) {
					font-size: 36rpx;
					font-weight: 700;
					color: #ff6c64;
				}
			}
		}

		.save {
			margin-top: 28rpx;

			text {
				font-size: 28rpx;
				color: #196bff;
			}
		}

		.list {
			padding-bottom: 10rpx;

			&-one {
				.clockIn-order-daka {
					width: 94%;
					background-color: #ffffff;
					padding: 30rpx 24rpx;
					box-sizing: border-box;
					border-radius: 12rpx;
					margin: 24rpx auto;

					&-left {
						&-top {
							text:nth-of-type(1) {
								font-weight: bold;
								color: #333333;
								font-size: 26rpx;
							}

							text:nth-of-type(2),
							text:nth-of-type(3) {
								margin: 0 20rpx;
							}

							text:nth-of-type(2),
							text:nth-of-type(3),
							text:nth-of-type(4) {
								color: #196bff;
								font-size: 26rpx;
							}
						}

						&-min {
							margin: 20rpx 0;

							text {
								color: #999999;
							}
						}

						&-bto {
							image {
								width: 32rpx;
								height: 32rpx;
								margin-right: 20rpx;
							}

							text {
								color: #999999;
							}
						}

						&-mark {
							margin-top: 20rpx;

							text {
								color: #999999;
							}
						}
					}

					&-image {
						image {
							width: 136rpx;
							height: 136rpx;
						}
					}
				}
			}
		}
	}
}

.isOutWork {
	border: 1px solid;
	padding: 2px 4px;
	border-radius: 5px;
}

.text-style {
	color: #196bff;
	font-size: 28rpx !important;
	margin: 0 10px;
}

.w-80 {
	width: 80%;
}
</style>
